package c.x.jy.admin.controller;

import java.util.*;
import java.util.stream.Collectors;

import c.x.jy.common.annotation.SysLog;
import c.x.jy.common.utils.Constant;
import c.x.jy.dao.entity.SysRoleEntity;
import c.x.jy.service.service.SysRoleMenuService;
import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import c.x.jy.dao.entity.SysMenuEntity;
import c.x.jy.service.service.SysMenuService;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.R;



/**
 * 菜单管理
 *
 * @author amwhyh
 * @email xxx@xx.com
 * @date 2021-05-20 20:25:04
 */
@RestController
@RequestMapping("sys/sysmenu")
public class SysMenuController extends AbstractController {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:sysmenu:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = sysMenuService.queryPage(params);

        return R.put(  page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions("sys:sysmenu:info")
    public R info(@PathVariable("menuId") Long menuId){
        SysMenuEntity sysMenu = sysMenuService.getById(menuId);

        return R .put(  sysMenu);
    }

    /**
     * 保存
     */
    @SysLog("添加菜单")
    @RequestMapping(value="/save",method= RequestMethod.POST)
    @RequiresPermissions("sys:sysmenu:save")
    public R save(@RequestBody SysMenuEntity sysMenu){
        sysMenuService.save(sysMenu);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改菜单")
    @RequestMapping(value="/update",method=RequestMethod.POST)
    @RequiresPermissions("sys:sysmenu:update")
    public R update(@RequestBody SysMenuEntity sysMenu){

        sysMenuService.updateById(sysMenu);

        return R.ok();
    }




    /**
     * 删除
     */
    @SysLog("删除菜单")
    @RequestMapping(value="/delete/{menuId}",method=RequestMethod.DELETE)
    @RequiresPermissions("sys:sysmenu:delete")
    public R delete(@PathVariable("menuId") Long menuId){
        if(menuId==null)return R.error("没有找到数据！");
        List<SysMenuEntity> list=	sysMenuService.list();
        List<Long>ids=new ArrayList<>();
        ids.add(menuId);
        getSonlist(list, menuId,ids) ;
        sysMenuService.removeByIds(ids);

        return R.ok();
    }


    private  void  getSonlist(List<SysMenuEntity> list,Long menuId,List<Long>ids){
        if(list==null||list.isEmpty())return  ;
        for (Iterator<SysMenuEntity> it = list.iterator(); it!=null&&it.hasNext() ; ) {
            SysMenuEntity  	d=it.next();
            if(d.getParentId().equals(menuId)) {
                ids.add(d.getMenuId());
                getSonlist(list, d.getMenuId(),ids);
            }

        }

    }


    /**
     * 两层循环实现建树
     *
     * @param sysMenus
     * @return
     */
    public static List<SysMenuEntity> treeBuilder(List<SysMenuEntity> sysMenus) {
        List<SysMenuEntity> menus = new ArrayList<>();
        for (SysMenuEntity sysMenu : sysMenus) {

            if (ObjectUtils.equals(Constant.MenuType.CATALOG.getValue(), sysMenu.getParentId().intValue())) {
                menus.add(sysMenu);
            }
            for (SysMenuEntity menu : sysMenus) {
                if (menu.getParentId().equals(sysMenu.getMenuId())) {
                    if (sysMenu.getSubMenus() == null) {
                        sysMenu.setSubMenus(new ArrayList<>());
                    }
                    sysMenu.getSubMenus().add(menu);
                }
            }
        }
        return menus  ;
    }


    /**
     * 当前登录用户的菜单
     *
     * @return
     */
    @GetMapping("/current")
    public R findMyMenu( ) {
        List<SysRoleEntity> roles = getUser().getRoles();

        List<SysMenuEntity> menus =null;
        if(getUser().getBusinessId().equals(Constant.SUPER_ADMIN)) {
            menus = sysMenuService.findByRoleCodes(null, null);
        }else {
            if (CollectionUtil.isEmpty(roles)) {
                return R.put(Collections.emptyList());
            }
            menus = sysMenuService.findByRoleCodes(roles.parallelStream().map(SysRoleEntity::getRoleId).collect(Collectors.toSet()), null);
        }

        return  R.put(treeBuilder(menus));
    }



    @GetMapping("/findAlls")
    @RequiresPermissions("sys:sysmenu:list")
    public R  findAlls() {
        return R.put(sysMenuService.list());
    }
    @GetMapping("/menus")
    @RequiresPermissions("sys:sysmenu:list")
    public R  menus() {
        return R.put(sysMenuService.findAlls());
    }



    @GetMapping("/{roleId}/menus")
    public R findMenusByRoleId(@PathVariable Long roleId) {
        Set<Long> roleIds = new HashSet<>();
        roleIds.add(roleId);
        //获取该角色对应的菜单
        List<SysMenuEntity> roleMenus = sysMenuService.findByRoleCodes(roleIds,null);
        //全部的菜单列表
        List<SysMenuEntity> allMenus = sysMenuService.list();
        List<Map<String, Object>> authTrees = new ArrayList<>();

        Map<Long, SysMenuEntity> roleMenusMap = roleMenus.stream().collect(Collectors.toMap(SysMenuEntity::getMenuId, SysMenu -> SysMenu));

        for (SysMenuEntity sysMenu : allMenus) {
            Map<String, Object> authTree = new HashMap<>();
            authTree.put("id", sysMenu.getMenuId());
            authTree.put("name", sysMenu.getName());
            authTree.put("pId", sysMenu.getParentId());
            authTree.put("open", true);
            authTree.put("checked", false);
            if (roleMenusMap.get(sysMenu.getMenuId()) != null) {
                authTree.put("checked", true);
            }
            authTrees.add(authTree);
        }
        return R.put(authTrees);
    }

    /**
     *
     * @param params
     * @return
     */
    @SysLog("修改角色菜单")
    @PostMapping("/granted")
    public R granted(@RequestBody Map<String, Object> params  ) {
        Object ro= params.get("roleId");
        if(ro==null)R.error("参数有误！");
        Long roleId= Long.valueOf( ro.toString()) ;
        List  menuIds= (List ) params.get("menuIds")  ;
        sysRoleMenuService.granted(menuIds,roleId);
        return R.ok();

    }

}

